<template>
  <view>
    <view class="form-view">
      <view class="form-item form-pa20 clearfix">
        <view class="float_left form-label">
          选择商铺
          <text class="icon-requird">*</text>
        </view>
        <view
          class="float_right form-value"
          @click="goPage('/pagesB/systemSet/ShopList?source=1')"
        >
          <text class="input-pl" v-if="!shop_name">请选择</text>
          <text v-else style="font-size: 30rpx">{{ shop_name }}</text>
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </view>
      <view class="form-item form-pa20 clearfix b20">
        <view class="float_left form-label">
          商品
          <text class="icon-requird">*</text>
        </view>
        <view
          class="float_right form-value"
          @click="selGoods"
          v-if="goods_list.length === 0"
        >
          <text class="input-pl">点击选择商品</text>
          <i class="ibonfont ibonjinru icon-jinru"></i>
        </view>
      </view>
      <view class="goods-ul">
        <view
          class="goods-item"
          v-for="(item, index) in goods_list"
          :key="index"
        >
          <view class="clearfix goods-goods">
            <view class="float_left goods-img"
              ><image :src="item.images[0]" mode="aspectFill"></image
            ></view>
            <view class="float_left goods-cont-right">
              <view class="goods-tit">{{ item.goodsName }}</view>
              <view class="goods-info">
                <text class="gi-label">编号：</text>
                <text class="gi-value">{{ item.code }}</text>
              </view>
            </view>
            <view class="del-view" @click="delData(index)">
              <u-icon name="close" size="32" color="#fb5904"></u-icon>
              ></view
            >
          </view>

          <view class="form-item form-pa20 b20 clearfix">
            <view class="float_left form-label">规格</view>
            <view class="float_right form-value">
              {{ item.unitName }}
              <block v-for="(itemU, indexU) in item.specGroup" :key="index"
                >_{{ itemU.specValueName }}</block
              >
            </view>
          </view>
          <view class="form-item form-pa20 clearfix">
            <view class="float_left form-label">启用阶梯价</view>
            <view class="float_right form-value"
              ><switch
                :checked="item.enabledLadder === 1"
                @change="enabledLadderChange(index)"
            /></view>
          </view>
          <view class="form-up">
            <view class="form-label">
              调整价格（元）
              <text class="icon-requird">*</text>
            </view>
            <view class="form-value">
              <input
                type="digit"
                v-if="parseInt(item.enabledLadder) === 0"
                placeholder="请输入价格"
                placeholder-class="input-pl"
                class="form-input"
                v-model="item.salePrice"
              />
              <view v-else>
                <ul v-if="parseInt(item.enabledLadder) === 1">
                  <li
                    class="ladder-price-item"
                    style="padding-bottom: 5px"
                    v-for="(itempp, indexpp) in item.ladderPrice"
                    :key="indexpp"
                  >
                    <input
                      class="ladder-price-input"
                      disabled
                      :value="itempp.from"
                      style="width: 60px"
                    />
                    --
                    <input
                      type="digit"
                      class="ladder-price-input"
                      v-if="!(indexpp === item.ladderPrice.length - 1)"
                      v-model="itempp.to"
                      :min="itempp.from + 1"
                      @blur="ladderPriceBlur(itempp.to, indexpp, index)"
                      style="width: 60px"
                    />
                    <input
                      class="ladder-price-input"
                      v-else
                      disabled
                      value="∞"
                      style="width: 60px"
                    />
                    {{ item.unitName }}
                    <input
                      type="digit"
                      class="ladder-price-input"
                      v-model="itempp.price"
                      style="width: 80px"
                    />
                    元
                    <i
                      @click="delLadderPrice(indexpp, index)"
                      class="ibonfont ibonshanchu del-icon"
                    ></i>
                  </li>
                  <li>
                    <button
                      @click="addLadderPrice(index)"
                      class="tag-item"
                      style="
                        background: #fb5904;
                        color: #fff;
                        border: none;
                        padding: 4px 12px;
                        border-radius: 6px;
                        font-size: 24upx;
                      "
                    >
                      <i class="ibonfont ibonxinzeng"></i>
                      新增
                    </button>
                  </li>
                </ul>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="fixed-bottom"
      ><view class="sub-btn" @click="checkSub">保存</view></view
    >
  </view>
</template>

<script>
function unique(arr, keys) {
  const map = new Map();
  arr.forEach((item) => {
    const key = keys.map((k) => item[k]).join("_");
    if (!map.has(key)) map.set(key, item);
  });
  return Array.from(map.values());
}

export default {
  data() {
    return {
      user_name: this.$store.state.userInfo.name || "",
      shop_name: "",
      shop_id: "",
      goods_list: [],
      shopSel: "",
      goodsData: "",
      goods_item: {},
    };
  },
  onLoad(options) {
    // 表单验证
    if (this.$refs.form) {
      this.$nextTick(() => {
        this.$refs.form.setRules(this.rules);
      });
    }
    if (!options.id) {
      uni.setNavigationBarTitle({
        title: "新增商品调价单",
      });
    } else {
      uni.setNavigationBarTitle({
        title: "修改商品调价单",
      });
    }
  },
  onShow() {
    // if (this.shopSel) {
    //   this.shop_id = this.shopSel.id;
    //   this.shop_name = this.shopSel.name;
    // }
    if (this.goodsData) {
      const goodsData = this.goodsData.map((item) => {
        return {
          images: item.images,
          code: item.code,
          createUserName: this.user_name || " ",
          goodsName: item.title,
          goodsId: item.id,
          saleType: "1",
          salePriceType: "1",
          salePriceAreaType: 1,
          salePrice: item.salePrice,
          nowPrice: item.salePrice,
          unitName: item.unitName,
          specGropName: item.specGroup
            ? item.specGroup
                .map((itemU) => {
                  return itemU.specValueName;
                })
                .join(";")
            : "",
          skuId: item.skuId,
          shopId: item.shopId,
          shopName: item.shopName,
          ladderPrice: item.ladderPrice,
          enabledLadder: item.enabledLadder,
        };
      });
      if (!this.goods_list.length) {
        this.goods_list = goodsData;
      } else {
        this.goods_list = unique(this.goods_list.concat(goodsData), [
          "id",
          "skuId",
        ]);
      }
      console.log(this.goods_list);
    }
    // 监听选择商铺事件
    if (!this._shopSelectedListener) {
      this._shopSelectedListener = (shop) => {
        if (!shop || !shop.id) return; // 增加健壮性校验
        this.shop_id = shop.id;
        this.shop_name = shop.name;
      };
      uni.$on("shop-selected", this._shopSelectedListener);
    }
  },
  onUnload() {
    // 移除事件监听，防止内存泄漏
    if (this._shopSelectedListener) {
      uni.$off("shop-selected", this._shopSelectedListener);
      this._shopSelectedListener = null;
    }
  },
  methods: {
    goPage(url) {
      uni.navigateTo({ url });
    },
    selGoods() {
      if (!this.shop_id) {
        this.$u.toast("请选择商铺");
        return;
      }
      this.goPage("/pagesT/goods/selGoods?shopId=" + this.shop_id);
      // this.goPage(
      //   `/pagesB/systemSet/GoodsSelList?shopId=${this.shop_id}&source=2`
      // );
    },
    delData(index) {
      this.goods_list.splice(index, 1);
    },
    checkSub() {
      const price = this.goods_list.map((item) => {
        return {
          ...item,
          ladderPrice: item.enabledLadder === 0 ? [] : item.ladderPrice,
          salePrice: item.enabledLadder === 1 ? 0 : item.salePrice,
          shopName: this.shop_name,
        };
      });
      let ladderPriceLength = true;
      let isLadderPrice = true;
      for (let i in price) {
        const item = price[i];
        if (item.enabledLadder === 1) {
          if (item.ladderPrice.length < 2) {
            ladderPriceLength = false;
            break;
          } else if (!item.ladderPrice.every((itemP) => itemP.price > 0)) {
            isLadderPrice = false;
            break;
          }
        } else {
          if (!item.salePrice) {
            isLadderPrice = false;
            break;
          }
        }
      }
      if (!ladderPriceLength) {
        this.$u.toast("请至少设置两条阶梯价");
        return;
      }
      if (!isLadderPrice) {
        this.$u.toast("请输入价格");
        return;
      }
      this.subData();
    },
    async subData() {
      const params = this.goods_list.map((item) => {
        if (item.ladderPrice.length) {
          item.ladderPrice[item.ladderPrice.length - 1].to = 9999999999;
        }

        // 获取最小的价格
        let min = 0;
        if (item.enabledLadder === 1) {
          const arr = item.ladderPrice.map((itemM) => {
            return itemM.price;
          });
          min = Math.min.apply(null, arr);
        }
        return {
          createUserName: item.createUserName || this.user_name || " ",
          goodsName: item.goodsName,
          goodsId: item.goodsId,
          saleType: item.saleType, // 1，实物销售，2，虚物销售
          salePriceType: item.salePriceType, // 1 销售价 2，秒杀价
          salePriceAreaType: item.salePriceAreaType,
          salePrice: {
            [item.skuId]: {
              salePrice: item.enabledLadder === 0 ? item.salePrice : min,
              unitName: item.specGropName,
              ladderPrice: item.enabledLadder === 0 ? [] : item.ladderPrice,
              marketPrice: item.nowPrice,
              enabledLadder: item.enabledLadder,
            },
          },
          shopId: item.shopId,
          shopName: this.shop_name,
        };
      });
      uni.showLoading();
      const { err, data } = await this.$u.api.PriceAdjustmentAdd(
        JSON.stringify(params)
      );
      uni.hideLoading();
      if (err) return;
      this.$u.toast("提交成功");
      uni.navigateBack();
    },
    // 删除阶梯价
    delLadderPrice(index, i) {
      const target = JSON.parse(JSON.stringify(this.goods_list));
      const priceData = target[i];
      if (priceData.ladderPrice.length === 2) {
        return;
      }
      priceData.ladderPrice.splice(index, 1);
      priceData.ladderPrice[0].from = 1;
      priceData.ladderPrice[priceData.ladderPrice.length - 1].from =
        Number(priceData.ladderPrice[0].to) + 1;
      this.goods_list = target;
    },
    // 新增一条阶梯价
    addLadderPrice(i) {
      // const target = this.$_util.deepClone(this.goods_list);
      const target = JSON.parse(JSON.stringify(this.goods_list));
      const priceData = target[i];
      if (priceData.ladderPrice.length === 3) {
        return;
      }
      if (!priceData.ladderPrice.length) {
        priceData.ladderPrice.push({
          from: 1,
          price: "",
          to: 2,
        });
      } else {
        const upL = priceData.ladderPrice[0];
        priceData.ladderPrice.splice(1, 0, {
          from: Number(upL.to) + 1,
          price: "",
          to: Number(upL.to) + 2,
        });
        if (priceData.ladderPrice.length === 3) {
          priceData.ladderPrice[priceData.ladderPrice.length - 1].from =
            Number(upL.to) + 3;
        }
      }
      this.goods_list = target;
    },

    ladderPriceBlur(val, index, i) {
      const target = JSON.parse(JSON.stringify(this.goods_list));
      const priceData = target[i];
      priceData.ladderPrice[index + 1].from = Number(val) + 1;
      if (index === 0) {
        priceData.ladderPrice[index + 1].to = Number(val) + 2;
        if (priceData.ladderPrice[index + 2]) {
          priceData.ladderPrice[index + 2].from = Number(val) + 3;
        }
      }
      this.goods_list = target;
    },
    enabledLadderChange(i) {
      const target = JSON.parse(JSON.stringify(this.goods_list));
      target[i].enabledLadder = target[i].enabledLadder === 1 ? 0 : 1;
      this.goods_list = target;
    },
  },
};
</script>

<style lang="scss">
$primary: #fb5904;

.form-view {
  background: #fff;
  border-radius: 16upx;
  margin: 24upx;
  box-shadow: 0 2upx 8upx rgba(251, 89, 4, 0.06); // 主题色
  padding: 10px;
}
.form-item {
  display: flex;
  align-items: center;
  padding: 24upx 0;
  // border-bottom: 1upx solid #f0f0f0;
  &.b20 {
    border-bottom: none;
  }
  .form-label {
    width: 180upx;
    color: #222;
    font-size: 30upx;
    font-weight: 500;
    .icon-requird {
      color: $primary;
      margin-left: 4upx;
    }
  }
  .form-value {
    flex: 1;
    color: #666;
    font-size: 28upx;
    display: flex;
    align-items: center;
    .input-pl {
      color: #bbb;
    }
    .icon-jinru {
      margin-left: 8upx;
      color: $primary;
    }
  }
}
.goods-ul {
  // margin: 0 0 24upx 0;
}
.goods-item {
  // border-bottom: 1upx solid #f5f5f5;
  padding: 20upx 0;
  background: #fff;
  border-radius: 12upx;
  margin-bottom: 16upx;
  box-shadow: 0 2upx 8upx rgba(251, 89, 4, 0.08); // 主题色
  .goods-goods {
    position: relative;
    display: flex;
    align-items: center;
    .goods-img {
      width: 120upx;
      height: 120upx;
      background: #f5f5f5;
      border-radius: 8upx;
      margin-right: 20upx;
      overflow: hidden;
      border: 2upx solid $primary;
      image {
        width: 100%;
        height: 100%;
        border-radius: 8upx;
        object-fit: cover;
      }
    }
    .goods-cont-right {
      width: 370upx;
      .goods-tit {
        padding-bottom: 10upx;
        width: 370upx;
        font-size: 30upx;
        color: #222;
        font-weight: 600;
        word-break: break-all;
      }
      .goods-info {
        padding-bottom: 10upx;
        font-size: 24upx;
        color: #666;
      }
    }
    .del-view {
      position: absolute;
      width: 50upx;
      height: 50upx;
      color: #fff;
      // background: $primary;
      border-radius: 100%;
      text-align: center;
      line-height: 50upx;
      right: 25upx;
      top: 50%;
      transform: translateY(-25upx);
      .ibonshanchu {
        font-size: 26upx;
      }
    }
  }
}
.ladder-price-input {
  display: inline-block;
  background: #f5f5f5;
  text-align: center;
  vertical-align: middle;
  border: 1upx solid $primary;
  border-radius: 6upx;
  padding: 4upx 0;
  margin: 0 4upx;
  font-size: 26upx;
  color: #222;
}
.del-icon {
  color: #dd524d;
  margin-left: 10upx;
  font-size: 26upx;
  cursor: pointer;
  transition: color 0.2s;
  &:active {
    color: #fb5904;
  }
}
.tag-item {
  background: $primary;
  color: #fff;
  border: none;
  padding: 4px 18px;
  border-radius: 8upx;
  font-size: 26upx;
  margin-top: 8upx;
  box-shadow: 0 2upx 8upx rgba(251, 89, 4, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  .ibonxinzeng {
    font-size: 28upx;
    margin-right: 6upx;
  }
}
.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2upx 8upx rgba(251, 89, 4, 0.06);
  padding: 24upx 0;
  .sub-btn {
    width: 90%;
    margin: 0 auto;
    background: $primary;
    color: #fff;
    border-radius: 48upx;
    font-size: 32upx;
    text-align: center;
    padding: 20upx 0;
    font-weight: 600;
    box-shadow: 0 4upx 16upx rgba(251, 89, 4, 0.12);
    border: none;
    transition: background 0.2s;
    &:active {
      background: #e04e00;
    }
  }
}
// 选中商品后高亮
.goods-item {
  // border: 2upx solid $primary;
}
</style>
